import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:date_format/date_format.dart';
import 'package:dio/dio.dart';
import 'package:helloworld/res/incomeData.dart';
import 'package:helloworld/tabs.dart';
import 'package:loading/loading.dart';
import 'package:loading/indicator/ball_pulse_indicator.dart';
import 'dart:ui';
class InCome extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _InCome();
  }
}
class _InCome extends State<InCome> with WidgetsBindingObserver{
  int _index;
  int flag = 1;
  Color _color;
  Color _textColor;
  Color _payColor;
  Color _incomeColor;
  Color _boxColor;
  Color _loadColor;
  _getData(String incomemonth,String incomeyear) async{
    Response response = await Dio().post("http://123.207.114.127:1314/income/selectByDate",queryParameters: {
      'incomemonth':incomemonth,
      'incomeyear':incomeyear
    });
    setState(() {
      if(response.data.length==0){
        flag = 0;
      }
      incomeData = response.data;
    });
  }
  Future<Null> _refresh()async{
    setState(() {
      flag =1;
      incomeData.clear();
    });
    await _getData('${formatDate(incomeDate, [mm, ])}','${formatDate(incomeDate, [yyyy, ])}');
    return;
  }
  _delete(int index,var context) async{
   await Dio().post("http://123.207.114.127:1314/income/deleteIncome",queryParameters: {
      'incomeid':incomeData[index]['incomeid']
    }).then((value){
      Navigator.pop(context);
   });

  }
  Widget loadingData(){
    if(incomeData.length==0&&flag==1){
      return Container(
          child: Center(
            child: Loading(indicator: BallPulseIndicator(), size: 100.0,color: _loadColor),
          ));
    }else if(incomeData.length==0&&flag==0){
      return Container(
          child: Center(
            child: ListView(
              children: <Widget>[
                SizedBox(height: 200,),
                Center(
                  child: Text('暂无收入信息',style: TextStyle(color: _textColor,fontSize: 30),),
                )
              ],
            ),
          ));
    } else{
      return ListView(
        physics:  AlwaysScrollableScrollPhysics(),
        children: incomeData.asMap().keys.map((f) {
          return Column(
            children: <Widget>[
              Container(
                decoration: BoxDecoration(
                      border: Border(
                          bottom: BorderSide(
                            // 设置单侧边框的样式
                              color: Colors.grey,
                              width: 0.3,
                              style: BorderStyle.solid))

                ),
                child: ListTile(
                  leading: Icon(
                    Icons.monetization_on,
                    size: 40,
                  ),
                  title: Text(incomeData[f]['incomename']),
                  subtitle: Text(incomeData[f]['incomedate']),
                  trailing: Text(
                    '+'+incomeData[f]['income'].toStringAsFixed(2),
                    style: TextStyle(fontSize: 15,color: _incomeColor),
                  ),
                  selected: f == _index,
                  onTap: () {
                    setState(() {
                      _index = f;
                      // Navigator.pushNamed(context, '/payDetail',
                      //     arguments: {'id': _index});
                    });
                  },
                  onLongPress: (){
                    showDialog(context: context,builder: (context){
                      return AlertDialog(
                        content: Text('您确定要删除吗?',style: TextStyle(fontSize: 20),),
                        actions: <Widget>[
                          FlatButton(
                            child: Text('取消',style: TextStyle(fontSize: 20),),
                            onPressed: (){
                              Navigator.pop(context);
                            },
                          ),
                          FlatButton(
                            child: Text('确定',style: TextStyle(fontSize: 20),),
                            onPressed: (){
                              _delete(f,context).then((value){
                                setState(() {
                                  incomeData.clear();
                                  _getData('${formatDate(incomeDate, [mm, ])}','${formatDate(incomeDate, [yyyy, ])}');
                                });
                              });


                            },
                          ),
                        ],
                      );
                    });
                  },
                ),
              ),
              // Padding(
              //   padding: EdgeInsets.fromLTRB(15, 0, 15, 0),
              //   child: Container(
              //     decoration: BoxDecoration(
              //       border: Border.all(width: 0.5,color: _boxColor),
              //     ),
              //   ),
              // ),
              SizedBox(height: 10,)
            ],
          );
        }).toList(),
      );
    }
  }
  Widget loadingTotal(){
    if(incomeData.length==0){
      return Text(
        '0.00',
        style: TextStyle(color: _payColor, fontSize: 30),
      );
    }else{
      return myIncome(_payColor);
    }
  }
  @override
  void didChangePlatformBrightness() {
    // TODO: implement didChangePlatformBrightness
    super.didChangePlatformBrightness();
    if(window.platformBrightness==Brightness.dark){
      _color = Colors.black45;
      _incomeColor = Colors.greenAccent;
      _loadColor = Colors.white;
      _textColor = Colors.white70;
      _payColor = Colors.white;
      _boxColor = Colors.grey;
    }else{
      _incomeColor = Colors.blue;
      _color = Colors.lightBlueAccent;
      _loadColor = Colors.blue;
      _textColor = Colors.black54;
      _payColor = Colors.black54;
      _boxColor = Colors.black26;
    }
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    if(window.platformBrightness==Brightness.dark){
      _color = Colors.black45;
      _incomeColor = Colors.greenAccent;
      _loadColor = Colors.white;
      _textColor = Colors.white70;
      _payColor = Colors.white;
      _boxColor = Colors.grey;
    }else{
      _incomeColor = Colors.blue;
      _color = Colors.lightBlueAccent;
      _loadColor = Colors.blue;
      _textColor = Colors.black54;
      _payColor = Colors.black54;
      _boxColor = Colors.black26;
    }
    _getData('${formatDate(incomeDate, [mm, ])}','${formatDate(incomeDate, [yyyy, ])}');
  }
  Future<bool> _back(){
    Navigator.pop(context);
    return new Future.value(false);
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return WillPopScope(
      child: Scaffold(
        appBar: AppBar(
          elevation: 0,
          title: Text("收入"),
          actions: <Widget>[
            InkWell(
              child: Padding(
                child: Row(
                  children: <Widget>[
                    Icon(Icons.add,color: Colors.white),
                    Text("添加",style: TextStyle(color: Colors.white, fontSize: 17),),
                  ],
                ),
                padding: EdgeInsets.all(16),
              ),
              onTap: (){
                Navigator.pushNamed(context, '/addIncome');
              },
            )
          ],
        ),
        body: Column(
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                  color: _color,
//              border: Border.fromBorderSide(),
                  boxShadow: [
                    BoxShadow(
                        color: Colors.black12,
                        offset: Offset(0.0, 5.0), //阴影xy轴偏移量
                        blurRadius: 15.0, //阴影模糊程度
                        spreadRadius: 1.0 //阴影扩散程度
                    )
                  ]
              ),
              height: 100,
              width: double.infinity,
              child: Row(
                children: <Widget>[
                  //时间
                  Expanded(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Container(
                          child: InkWell(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                Text('${formatDate(incomeDate, [yyyy, '年'])}',style: TextStyle(fontSize: 15,color: _textColor),),
                                Row(
                                  children: <Widget>[
                                    Text('${formatDate(incomeDate, [mm, '月'])}',style: TextStyle(fontSize: 25,color: _payColor),),
                                    Icon(Icons.arrow_drop_down)
                                  ],
                                )

                              ],
                            ),
                            onTap: (){
                              DatePicker.showDatePicker(
                                context,
                                onMonthChangeStartWithFirstDate: true,
                                pickerTheme: DateTimePickerTheme(
                                  showTitle: true,
                                  confirm: Text('确定', style: TextStyle(color: Colors.black54,fontSize: 20)),
                                  cancel: Text('取消', style: TextStyle(color: Colors.black54,fontSize: 20)),
                                ),
                                minDateTime: DateTime.parse('2020-01-01'),
                                maxDateTime: DateTime.parse('2099-12-31'),
                                initialDateTime: DateTime.now(),
                                dateFormat: 'yyyy-MMMM',
                                locale: DateTimePickerLocale.zh_cn,
                                onConfirm: (dateTime, List<int> index) {
                                  setState(() {
                                    incomeDate = dateTime;
                                    _refresh();
                                  });

                                },
                              );
                            },
                          ),
                        )
                      ],
                    ),
                    flex: 1,
                  ),

                  //竖线
                  Expanded(
                    child: Container(
                      height: 40,
                      width: 1,
                      decoration: BoxDecoration(
                          border: Border.all(color: _boxColor)
                      ),
                    ),
                    flex: 0,
                  ),
                  //支出
                  Expanded(
                    child: Container(
                      padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
                      child: Column(
                        children: <Widget>[
                          Padding(
                            padding: EdgeInsets.fromLTRB(0, 5, 0, 0),
                            child: Text('月收入',style: TextStyle(fontSize: 15,color: _textColor),),
                          ),
                          loadingTotal()
                        ],
                      ),
                    ),
                    flex: 2,
                  )

                ],
              ),
            ),
            SizedBox(
              height: 10,
            ),
            Expanded(
              child: Container(
                child: RefreshIndicator(
                  displacement: 20,
                  child: loadingData(),
                  onRefresh: _refresh,
                ),
                padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
              ),
            ),
          ],
        ),
      ),
      onWillPop: _back,
    );
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }
}
class myIncome extends StatelessWidget {
  Color _payColor;
  double _totalIncome = 0;
  myIncome(Color payColor) {
    _payColor = payColor;
    for (int i = 0; i < incomeData.length; i++) {
      _totalIncome = _totalIncome + incomeData[i]['income'];
    }
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Text(
      '+'+_totalIncome.toStringAsFixed(2),
      style: TextStyle(color: _payColor, fontSize: 30),
    );
  }
}